var express = require('express');
var router = express.Router();
const jwt = require('jsonwebtoken');
var { userModel } = require('../../model/model');

//引入阿里云短信服务模块
const SMSClient = require('@alicloud/sms-sdk');


// 注册
router.post('/register', async (req, res) => {
    let { username, password, phone } = req.body;
    let findUser = await userModel.find({ username:username,phone:phone })
    if (findUser.length === 0) {
        await userModel.create({ username, password, phone })
        res.send({
            code: 200,
            msg: "注册成功"
        })
    } else {
        res.send({
            code: 201,
            msg: "该用户已经注册过，请勿重复注册"
        })
    }
})

// 产生6位随机数(用来生成短信验证码的)
function getCode() {
    let str = "";
    for (let i = 0; i < 6; i++) {
        str += parseInt(Math.random() * 10)
    }
    return str;
}



// //  */phone
router.post('/getcodes', async (req, res) => {
    let phoneNum = req.body.phone;  //获取前端参数phone
    console.log("手机号码", phoneNum);
    try {
        let findPhone = await userModel.findOne({ phone: phoneNum });
        console.log("findPhone111111111111", findPhone);
        if (findPhone) {
            //初始化sms_client  阿里云接口-密钥id和密钥
            let smsClient = new SMSClient({
                accessKeyId: 'LTAI5t7P1wZoE6GaLBxipuuJ',  //accessKeyId 前面提到要准备的
                secretAccessKey: 'JFNXaJZQb4NUqqO7mcXZnad4nBR4PC'  //secretAccessKey 前面提到要准备的
            });
            console.log(smsClient,'lllllll');
            // 6位随机数
            let str = getCode();
            // 开始发送短信
            smsClient.sendSMS({
                PhoneNumbers: phoneNum,
                SignName: "模拟APP", //签名名称 前面提到要准备的
                TemplateCode: "SMS_465661086", //模版CODE  前面提到要准备的
                TemplateParam: `{"code":'${str}'}`, // 短信模板变量对应的实际值，JSON格式
            }).then(result => {
                console.log("result", result)
                let { Code } = result;
                if (Code == 'OK') {
                    res.json({
                        code: 0,
                        msg: 'success',
                        sms: str
                    })
                    console.log(result)
                }
            })
        } else {
            res.send({
                code: 201,
                msg: '手机号不正确'
            })
        }
    }
    catch (error) {
        res.send({
            code: 202,
            msg: '发送失败',
            error: error.message
        })
    }
})

// 登录、注册并登录
router.post('/login', async (req, res) => {
    let { phone } = req.body
    console.log(phone, 'ppppppppppp');
    const findUser = await userModel.findOne({ phone })
    console.log(findUser, 'findUser');
    if (findUser) {
        let accessToken = "Bearer" + jwt.sign({ phone }, 'lyc123', { expiresIn: '10s' })
        let refreshToken = "Bearer" + jwt.sign({ phone }, 'lyc123', { expiresIn: '1h' })
        res.send({
            code: 200,
            msg: '登录成功',
            accessToken,
            refreshToken
        })
    } else {
        let newUser = new userModel({ phone })
        await newUser.save()
        let accessToken = "Bearer" + jwt.sign({ phone }, 'lyc123', { expiresIn: '10s' })
        let refreshToken = "Bearer" + jwt.sign({ phone }, 'lyc123', { expiresIn: '1h' })
        res.send({
            code: 200,
            msg: '注册成功并登录',
            accessToken,
            refreshToken
        })
    }
})



router.get('/getUser', async (req, res) => {
    let users = await userModel.find()
    res.send({
        code: 200,
        msg: '查询成功',
        data: users
    })
})

router.post("/refreshtoken", async (req, res) => {
    const { refreshtoken, tel } = req.body;
    console.log(refreshtoken);
    //验证refreshToken的有效性
    if (!refreshtoken) {
        res.send({
            code: 401,
            msg: "刷新token失败"
        })
    } else {
        jwt.verify(refreshtoken, "123456", async (err, decoded) => {
            let accesstoken = "Bearer " + jwt.sign({ tel }, "123456", { expiresIn: "1m" });
            console.log("====", accesstoken);
            res.send({
                code: 200,
                msg: "刷新成功",
                accesstoken
            })
        });
    }
})



module.exports = router;
